package mspbots.cw.data.core;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Jay Yang
 */
public abstract class AbstractToolsUtil {

    protected R2dbcEntityTemplate r2dbcEntityTemplate;

    protected ObjectMapper objectMapper;

    protected LocalDateTime getUpdateTime(JsonNode resultNode) {
        JsonNode timeNode = resultNode.findValue("lastUpdated");
        return ObjectUtils.isEmpty(timeNode) ? LocalDateTime.now() :
                LocalDateTime.parse(timeNode.asText(), DateTimeFormatter.ISO_ZONED_DATE_TIME);
    }

    protected LocalDateTime getCreateTime(JsonNode resultNode) {
        JsonNode timeNode = resultNode.findValue("dateEntered");
        return ObjectUtils.isEmpty(timeNode) ? LocalDateTime.now() :
                LocalDateTime.parse(timeNode.asText(), DateTimeFormatter.ISO_ZONED_DATE_TIME);
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setR2dbcEntityTemplate(R2dbcEntityTemplate r2dbcEntityTemplate) {
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
    }
}
